package com.zucc.util;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.cglib.core.Converter;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : charspan
 * @Description :
 * @create : 2021-11-29 4:59 下午
 */
@Slf4j
public class MyBeanUtil {
    private MyBeanUtil() {

    }

    /**
     * 简单的深度bean copy
     *
     * @param from
     * @param to
     * @param <T>
     * @param <V>
     * @return
     */
    public static <T, V> T copyProperties(V from, Class<T> to) {
        if (from == null) {
            return null;
        }
        Class<?> clazz = from.getClass();
        BeanCopier copier = BeanCopier.create(clazz, to, false);
        T t = null;
        try {
            t = to.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("error");
        }
        copier.copy(from, t, null);
        return t;
    }

    /**
     * 带特定转换的深度bean copy
     *
     * @param from
     * @param to
     * @param <T>
     * @param <V>
     * @return
     */
    public static <T, V> T converterCopyProperties(V from, Class<T> to, Converter converter) {
        if (from == null) {
            return null;
        }
        Class<?> clazz = from.getClass();
        BeanCopier copier = BeanCopier.create(clazz, to, true);
        T t = null;
        try {
            t = to.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("error");
        }
        copier.copy(from, t, converter);
        return t;
    }

    /**
     * list 转化
     *
     * @param from
     * @param to
     * @param <T>
     * @param <V>
     * @return
     */
    public static <T, V> List<T> converterList(final List<V> from, final Class<T> to) {
        if (from == null || from.isEmpty()) {
            return Lists.newArrayList();
        }
        return from.stream().map((V input) -> {
            T t = null;
            try {
                t = MyBeanUtil.copyProperties(input, to);
            } catch (Exception e) {
                log.error("bean copy error!!", e);
            }
            return t;
        }).collect(Collectors.toList());
    }
}
